package entityMapping.demo3.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Repository
@Transactional
public class BaseDaoImpl<T> implements BaseDao<T> {

    @Autowired
    SessionFactory factory;

    // 无需手动关闭 Session 连接
    private Session getSession() {
        return factory.getCurrentSession();
    }

    @Override
    public Serializable save(T record) {
        return getSession().save(record);
    }

    @Override
    public List<T> recover(Class<T> clazz) {
        CriteriaQuery<T> criteriaQuery = getSession().getCriteriaBuilder().createQuery(clazz);
        Root<T> root = criteriaQuery.from(clazz);
        criteriaQuery.select(root);
        return getSession().createQuery(criteriaQuery).getResultList();
    }

    @Override
    public List<T> recover(Class<T> clazz, Predicate... predicates) {
        CriteriaBuilder cb = getSession().getCriteriaBuilder();
        CriteriaQuery<T> query = cb.createQuery(clazz);
        query.where(predicates);
        return getSession().createQuery(query).list();
    }

    @Override
    public void delete(T record) {
        getSession().delete(record);
    }

    @Override
    public void update(T record) {
        getSession().update(record);
    }

    @Override
    public void saveOrUpdate(T record) {
        getSession().saveOrUpdate(record);
    }
}
